package ogameplayer.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.spi.LoggingEvent;
import org.rulix.ogame.player.api.OgameCoreLogic;
import org.rulix.ogame.player.api.OgameFleetMovement;
import org.rulix.ogame.player.api.OgameLogicFactory;
import org.rulix.ogame.player.api.OgameLogicListener;
import org.rulix.ogame.player.api.OgameLoginStatus;
import org.rulix.ogame.player.core.OgameException;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class TextUI extends JFrame implements OgameLogicListener {

	private static Logger logger = Logger.getLogger("op.gui");
	private JPanel contentPane;
	private JTextField textField;
	private List<String> comands = Collections.synchronizedList(new ArrayList<String>());
	private int cmdIndex = 0;
	private JButton btnNewButton;
	private JPanel panel;
	private OgameCoreLogic ocl;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		BasicConfigurator.configure();
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					TextUI frame = new TextUI();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public TextUI() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 397);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		JTextArea textArea = new JTextArea();
		contentPane.setLayout(new BorderLayout(0, 0));
		
		panel = new JPanel();
		contentPane.add(panel, BorderLayout.NORTH);
		panel.setLayout(new BorderLayout(0, 0));
		
		
		textField = new JTextField();
		panel.add(textField, BorderLayout.CENTER);
		textField.setColumns(10);
		
		btnNewButton = new JButton("Execute");
		panel.add(btnNewButton, BorderLayout.EAST);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String text = textField.getText();
				if ( ! text.trim().equals("") ) {
					performOperation(text);
					comands.add(text);
				}
				textField.setText("");
				cmdIndex = comands.size();
			}
		});
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if ( e.getKeyCode() == KeyEvent.VK_UP ) {
					cmdIndex--;
					if (cmdIndex < 0 )
						cmdIndex = comands.size();
				} else if ( e.getKeyCode() == KeyEvent.VK_DOWN ) {
					cmdIndex++;
					if ( cmdIndex > comands.size() )
						cmdIndex = 0;
				} else if ( e.getKeyCode() == KeyEvent.VK_ENTER ) {
					btnNewButton.doClick(0);
				} else {
					return;
				}
				
				if ( cmdIndex == comands.size() )
					textField.setText("");
				else
					textField.setText(comands.get(cmdIndex));
				
			}
		});
		contentPane.add(textArea);
		init();
	}

	
	
	
	
	private void performOperation(String cmd){
		logger.debug("Command " +cmd);
		
		if ( cmd.equalsIgnoreCase("login")){
			try {
				ocl.logIn("uni58.ogame.com.es", "rulix", "11223344");
			} catch (OgameException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if ( cmd.equalsIgnoreCase("getFleets")){
			try {
				ocl.getFleetMovements();
			} catch (OgameException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	
	public static class TextAreaAppender extends WriterAppender {
		
		private JTextArea jTextArea = null;
		
		/** Set the target JTextArea for the logging information to appear. */
		public void setTextArea(JTextArea jTextArea) {
			this.jTextArea = jTextArea;
		}
		/**
		 * Format and then append the loggingEvent to the stored
		 * JTextArea.
		 */
		public void append(LoggingEvent loggingEvent) {
			final String message = this.layout.format(loggingEvent);

			// Append formatted message to textarea using the Swing Thread.
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					jTextArea.append(message);
				}
			});
		}
	}
	
	
	// init
	private void init() {
		ocl = OgameLogicFactory.getLogic();
		ocl.init();
		ocl.addOgameLogicListener(this);
		
	}

	@Override
	public void loginChangeStatus(OgameLoginStatus ogameLoginStatus) {
		logger.debug("Login status changed: ["+ ogameLoginStatus + "]");
	}
	
	@Override
	public void fleetMovementsAvailable(List<OgameFleetMovement> fleetMovements) {
		for (OgameFleetMovement ogameFleetMovement : fleetMovements) {
			logger.debug(" - Fleet Movement " + ogameFleetMovement);
		}
	}
}
